package com.yj.cmp.sdk.fusioncompute.storage.volume;

import com.yj.cmp.sdk.fusioncompute.common.utils.RequestUtils;
import com.yj.cmp.sdk.fusioncompute.storage.volume.dto.CreateVolumeDto;
import com.yj.cmp.sdk.fusioncompute.storage.volume.vo.CreateVolumeVo;
import com.yj.cmp.sdk.fusioncompute.storage.volume.vo.VolumeDetailVo;
import com.yj.cmp.sdk.fusioncompute.storage.volume.vo.VolumeListVo;
import org.springframework.stereotype.Component;
import retrofit2.Response;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Harvey_Yang
 * @date 2021/8/28 11:16
 */
@Component
public class FcVolumeApi {
    FcVolumeService fcVolumeService;

    public FcVolumeApi(FcVolumeService fcVolumeService) {
        this.fcVolumeService = fcVolumeService;
    }

    /**
     * 数据卷列表
     */
    public List<VolumeListVo.VolumesDTO> volumeList(Map<String, Object> headerMap, Map<String, Object> queryParam) throws Exception {
        List<VolumeListVo.VolumesDTO> list = new ArrayList<>();

        Response<VolumeListVo> response = fcVolumeService.volumeList(headerMap, queryParam).execute();
        RequestUtils.isSuccessful(response);
        list.addAll(response.body().getVolumes());
        if (response.body().getTotal() <= 100) {
            if (null != response.body()) {
                return response.body().getVolumes();
            }
            return new ArrayList<>(0);
        }

        int page = (int) Math.ceil(new Double(response.body().getTotal()) / 100);
        for (int i = 2; i <= page; i++) {
            queryParam.put("offset", i);
            queryParam.put("limit", 100);
            list.addAll(fcVolumeService.volumeList(headerMap, queryParam).execute().body().getVolumes());
        }
        return list;
    }

    /**
     * 数据卷详细
     */
    public VolumeDetailVo volumeDetail(Map<String, Object> headerMap, String volumeId) throws Exception {
        Response<VolumeDetailVo> response = fcVolumeService.volumeDetail(headerMap, volumeId).execute();
        RequestUtils.isSuccessful(response);
        if (null != response.body()) {
            return response.body();
        }
        return new VolumeDetailVo();
    }

    /**
     * 创建数据卷
     */
    public CreateVolumeVo createVolume(Map<String, Object> headerMap, CreateVolumeDto createVolumeDto) throws Exception {
        Response<CreateVolumeVo> response = fcVolumeService.createVolume(headerMap, createVolumeDto).execute();
        RequestUtils.isSuccessful(response);
        if (null != response.body()) {
            return response.body();
        }
        return new CreateVolumeVo();
    }
}
